package db

import (
	myDB "db/mysql"
	"fmt"
	"time"
)

// 用户文件信息
type UserFile struct {
	UserName    string
	FilePath    string
	FileName    string
	FileSize    int64
	UploadAt    string
	LastUpdated string
	FileHash    string
}

//更新用户文件表
func OnUserFileUploadFinished(userName, fileHash, fileName string, fileSize int64) bool {
	statement, err := myDB.GetDBConn().Prepare("insert ignore into tbl_user_file " +
		"(user_name, file_sha1, file_size, file_name, upload_at) values (?,?,?,?,?)")
	if err != nil {
		fmt.Printf("OnUserFileUploadFinished to statement, err:" + err.Error())
		return false
	}

	defer statement.Close()

	_, err = statement.Exec(userName, fileHash, fileSize, fileName, time.Now())
	if err != nil {
		fmt.Printf("OnUserFileUploadFinished to Exec, err:" + err.Error())
		return false
	}
	return true
}

func QueryUserFileMetas(username string, limit int) ([]UserFile, error) {
	statement, err := myDB.GetDBConn().Prepare("select file_sha1, file_name, file_size, upload_at,last_update " +
		"from tbl_user_file " +
		"where user_name = ? and status = 0 limit ?")
	if err != nil {
		fmt.Printf("QueryUserFileMetas to statement, err:" + err.Error())
		return nil, err
	}
	defer statement.Close()
	rows, err := statement.Query(username, limit)
	if err != nil {
		fmt.Printf("QueryUserFileMetas to Query, err:" + err.Error())
		return nil, err
	}
	var userFiles []UserFile
	for rows.Next() {
		ufile := UserFile{}
		err := rows.Scan(&ufile.FileHash, &ufile.FileName, &ufile.FileSize, &ufile.UploadAt, &ufile.LastUpdated)
		if err != nil {
			fmt.Printf("QueryUserFileMetas to Scan, err:" + err.Error())
			break
		}
		userFiles = append(userFiles, ufile)
	}
	return userFiles, nil
}

//修改文件名稱
func UpdateUserFileName(fileSha1 string, newName string, username string) bool {
	statement, err := myDB.GetDBConn().Prepare("update tbl_user_file set file_name = ?,last_update = current_time where file_sha1 = ? and user_name = ?")
	if err != nil {
		fmt.Printf("UpdateUserFileName to statement, err:" + err.Error())
		return false
	}
	defer statement.Close()
	result, err := statement.Exec(newName, fileSha1, username)
	if affected, err := result.RowsAffected(); err == nil {
		if affected <= 0 {
			fmt.Printf("UpdateUserFileName with hash:%s has not uploaded", fileSha1)
			return false
		}
		return true
	}
	return true
}

//修改文件名稱
func DeleteUserFileName(fileSha1 string, username string) bool {
	statement, err := myDB.GetDBConn().Prepare("update tbl_user_file set statuts = 1,last_update = current_time where file_sha1 = ? and user_name = ?")
	if err != nil {
		fmt.Printf("DeleteUserFileName to statement, err:" + err.Error())
		return false
	}
	defer statement.Close()
	result, err := statement.Exec(fileSha1, username)
	if affected, err := result.RowsAffected(); err == nil {
		if affected <= 0 {
			fmt.Printf("DeleteUserFileName with hash:%s has not uploaded", fileSha1)
			return false
		}
		return true
	}
	return true
}
